#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: mixins.py
@contact: zwb15083976291@163.com
@time: 2021/11/11
"""
import hashlib
import logging

from django.conf import settings

from admin.serializers.user import AdminTokenSerializer
from utils.token import TokenGenerator
from utils.redis_clients import RedisClient

logger = logging.getLogger("default")


class AdminLoginMixin(object):

    @property
    def token_serializer(self):
        return TokenGenerator(secret_key=getattr(settings, "SECRET_KEY"),
                              salt=getattr(settings, "TOKEN_SALT"),
                              expires_in=getattr(settings, "TOKEN_EXPIRES_IN"))

    def generate_token(self, user):
        auth_dict = AdminTokenSerializer(user).data
        token = self.token_serializer.encryption_token(auth_dict)
        RedisClient().set(key=getattr(settings, "BLOG_SALT_KEY"), value=token,
                          ex=getattr(settings, "TOKEN_EXPIRES_IN"))
        return dict(token=token)

    def login_out(self):
        try:
            ret = RedisClient().pipeline().expire(getattr(settings, "BLOG_SALT_KEY"), 0)
        except Exception as e:
            logger.error(e)
            return False
        return ret
